/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the srsb4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.zyw.srsb.admin.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.amazonaws.services.s3.model.S3Object;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyw.srsb.admin.api.entity.SysFile;
import com.zyw.srsb.admin.config.AliOssConfig;
import com.zyw.srsb.admin.mapper.SysFileMapper;
import com.zyw.srsb.admin.service.SysFileService;
import com.zyw.srsb.common.core.util.R;
import com.pig4cloud.plugin.oss.OssProperties;
import com.pig4cloud.plugin.oss.service.OssTemplate;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件管理
 *
 * @author 朱耀威
 * @date 2021/12/13
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements SysFileService {

	private final OssProperties ossProperties;

	private final OssTemplate minioTemplate;

	private final AliOssConfig aliOssConfig;

	/**
	 * 上传文件 这里进行二次开发，修改成使用阿里oss上传文件
	 * @param file
	 * @return
	 */
	@Override
	public R uploadFile(MultipartFile file) {
		String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
		String endpoint = aliOssConfig.getEndpoint();
		String accessKeyId = aliOssConfig.getAccessKeyId();
		String accessKeySecret = aliOssConfig.getAccessKeySecret();
		// 创建OSSClient实例
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		StringBuilder url = new StringBuilder(aliOssConfig.getBaseUrl()).append("/").append(aliOssConfig.getBaseDir()).append("/").append(fileName);
		// 将MultipartFile文件转换成file文件
		try {
			PutObjectRequest putObjectRequest = new PutObjectRequest(aliOssConfig.getBucket(), aliOssConfig.getBaseDir()+"/"+fileName, file.getInputStream());
			PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
			// 文件管理数据记录,收集管理追踪文件
			fileLog(file, fileName,url.toString());
		}catch (IOException e){
			log.info("{}",e);
			return R.failed(e);
		}finally {
			ossClient.shutdown();
		}

		Map<String, String> resultMap = new HashMap<>(4);
		resultMap.put("bucketName", aliOssConfig.getBucket());
		resultMap.put("fileName", fileName);
		resultMap.put("url", url.toString());
		resultMap.put("everything",aliOssConfig.toString());


		return R.ok(resultMap);
	}

	/**
	 * 读取文件
	 * @param bucket
	 * @param fileName
	 * @param response
	 */
	@Override
	public void getFile(String bucket, String fileName, HttpServletResponse response) {
		try (S3Object s3Object = minioTemplate.getObject(bucket, fileName)) {
			response.setContentType("application/octet-stream; charset=UTF-8");
			IoUtil.copy(s3Object.getObjectContent(), response.getOutputStream());
		}
		catch (Exception e) {
			log.error("文件读取异常: {}", e.getLocalizedMessage());
		}
	}

	/**
	 * 删除文件
	 * @param id
	 * @return
	 */
	@Override
	@SneakyThrows
	@Transactional(rollbackFor = Exception.class)
	public Boolean deleteFile(Long id) {
		SysFile file = this.getById(id);
		delAliOssFile(file.getOriginal());
		return this.removeById(id);
	}

	/**
	 * 文件管理数据记录,收集管理追踪文件
	 * @param file 上传文件格式
	 * @param fileName 文件名
	 */
	private void fileLog(MultipartFile file, String fileName,String url) {
		SysFile sysFile = new SysFile();
		sysFile.setFileName(fileName);
		sysFile.setOriginal(file.getOriginalFilename());
		sysFile.setFileSize(file.getSize());
		sysFile.setType(FileUtil.extName(file.getOriginalFilename()));
		sysFile.setBucketName(aliOssConfig.getBucket());
		sysFile.setFileUrl(url);
		this.save(sysFile);
	}

	/**
	 * 文件管理文件删除，阿里oss文件删除api
	 */
	private void delAliOssFile(String objectName){
		String endpoint = aliOssConfig.getEndpoint();
		String accessKeyId = aliOssConfig.getAccessKeyId();
		String accessKeySecret = aliOssConfig.getAccessKeySecret();
		String bucketName = aliOssConfig.getBucket();
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		ossClient.deleteObject(bucketName,aliOssConfig.getBaseDir()+"/"+objectName);
		ossClient.shutdown();
	}

	/**
	 * 空字符串
	 */
	private static final String EMPTY_STR = "";

}
